<template>
  <div class="group-send">
    <!-- tabs -->
    <div class="filter-box">
      <!-- 切换tab -->
      <div class="tab-title">
        <p class="can-not-select" :class="{ tabChose: currentTab === 'friendsTab' }" @click="currentTab = 'friendsTab'">
          好友群发
        </p>
        <p class="can-not-select" :class="{ tabChose: currentTab === 'roomsTab' }" @click="currentTab = 'roomsTab'">
          群推送
        </p>
      </div>
      <!-- 标签列表 -->
      <ul v-show="!searchContent" class="labels-list scroll">
        <!-- 好友 -->
        <template v-if="currentTab === 'friendsTab'">
          <!-- 全选 -->
          <li
            class="label-item"
            :class="{ 'current-label': currentLabel === 'allFriends' }"
            @click="showFriends('allFriends')"
          >
            <input
              type="checkbox"
              style="margin-left: 5px"
              :checked="friendsChecked.length === friends.length"
              @click="choseFriendsByLabel($event, 'allFriends')"
            />
            <p v-text="'全部好友'"></p>
          </li>
          <!-- 选择标签 -->
          <li
            v-for="(label, index) in labels"
            :key="index"
            class="label-item"
            :class="[
              { 'current-label': currentLabel === label.LabelId },
              { 'label-disabled': friendsOfEveryLabel[label.LabelId].length === 0 }
            ]"
            @click="friendsOfEveryLabel[label.LabelId].length === 0 ? '' : showFriends(label.LabelId)"
          >
            <input
              type="checkbox"
              style="margin-left: 5px"
              :checked="
                friendsOfEveryLabel[label.LabelId].length !== 0 &&
                  friendsOfEveryLabel[label.LabelId].length === friendsCheckedByLabel[label.LabelId].length
              "
              @click="choseFriendsByLabel($event, label.LabelId)"
            />
            <p class="ellipsis">{{ label.LabelName }}({{ friendsOfEveryLabel[label.LabelId].length }})</p>
          </li>
        </template>
        <!-- 群 -->
        <template v-else>
          <!-- 全选 -->
          <li
            class="label-item"
            :class="{ 'current-label': currentRoomLabel === 'allFriends' }"
            @click="showFriends('allFriends')"
          >
            <input
              type="checkbox"
              style="margin-left: 5px"
              :checked="roomsChecked.length === chatRooms.length"
              @click="choseRoomsByLabel($event, 'allFriends')"
            />
            <p v-text="'全部群组'"></p>
          </li>
        </template>
      </ul>
    </div>

    <!-- 好友列表 -->
    <div v-if="currentTab === 'friendsTab'" class="friends-list">
      <!-- search -->
      <div class="friends-list-title">
        <p>好友列表</p>
        <!-- 搜索 -->
        <el-input
          v-model.lazy="searchContent"
          class="search-input"
          size="mini"
          suffix-icon="el-icon-search"
          type="text"
          placeholder="输入昵称搜索"
        ></el-input>
      </div>

      <!-- table -->
      <el-table v-if="forceRefresh" class="scroll" :data="tableDataPage[currentPage - 1]" stripe>
        <el-table-column type="index" :index="indexMethod" label="序号" width="60px"></el-table-column>
        <el-table-column label="昵称" prop="FriendNick"></el-table-column>
        <el-table-column label="头像" width="60px" style="border: solid red 1px">
          <template slot-scope="scope">
            <el-image style="width: 30px; height: 30px" :src="scope.row.Avatar">
              <div slot="error" class="image-slot">
                <i style="font-size: 30px" class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="备注名" prop="Memo"></el-table-column>
        <!-- <el-table-column label="标签">
            <template slot-scope="scope">
              <el-tag
                v-for="(labelId, index) in formatLabelId(scope.row.LabelIds)"
                :key="index"
                class="label"
                v-text="$options.filters.labelFilter(labelId, labels)"
              ></el-tag>
            </template>
          </el-table-column> -->
        <el-table-column width="100px">
          <template slot="header">
            <!-- <div class="all-check">
                <input
                  id="table-all-checked"
                  style="border-color: #409eff; margin: auto 5px"
                  type="checkbox"
                  disabled
                  :checked="tableAllChecked"
                  @click="choseAllData($event)"
                />
                <label for="table-all-checked">全 选</label>
              </div> -->
          </template>
          <template slot-scope="scope">
            <input
              v-if="currentLabel === 'allFriends'"
              type="checkbox"
              style="margin-left: 5px"
              :checked="friendsChecked.indexOf(scope.row.FriendId) >= 0"
              @click="choseFriend($event, scope.row)"
            />
            <input
              v-else
              type="checkbox"
              style="margin-left: 5px"
              :checked="friendsCheckedByLabel[currentLabel].indexOf(scope.row.FriendId) >= 0"
              @click="choseFriend($event, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin: 5px auto 0"
        :current-page="currentPage"
        :page-sizes="[50, 100, 150, 200]"
        :page-size="pageSize"
        :pager-count="7"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <ul v-else class="chat-rooms-list scroll">
      <li
        v-for="(room, index2) in chatRooms"
        :key="index2"
        class="room-item"
        :class="{ 'room-item-3x': index2 % 3 === 2 }"
      >
        <el-avatar style="min-width: 34px; margin-right: 5px" :size="34" shape="square" :src="room.Avatar">
          <i class="fa fa-picture-o" aria-hidden="true" title="头像miss"></i>
        </el-avatar>
        <p class="ellipsis" v-text="room.NickName"></p>
        <!-- <input type="checkbox" name="reading" checked /> -->
        <input type="checkbox" :checked="roomsChecked.indexOf(room.UserName) >= 0" @click="choseRoom($event, room)" />
      </li>
    </ul>

    <!-- 展示已选的好友|群 -->
    <div class="friends-chosed">
      <div class="third-box-title">
        <p style="color: #999999" v-text="currentTab === 'friendsTab' ? '已选好友' : '已选群组'"></p>
        <p v-if="currentTab === 'friendsTab'">
          已选
          <span style="color: #ff0000" v-text="finalFriendsInfo.length"></span>
          人
        </p>
        <p v-else>
          已选
          <span style="color: #ff0000" v-text="roomsChecked.length"></span>
          个
        </p>
      </div>

      <div class="friends-chose-list scroll">
        <el-tag
          v-for="(friend, index) in currentTab === 'friendsTab' ? finalFriendsInfo : roomsCheckedInfo"
          :key="index"
          style="margin: 5px"
          closable
          type="info"
          @close="currentTab === 'friendsTab' ? removeFriend(friend) : removeRoom(friend)"
        >
          {{ friend.FriendNick || friend.NickName }}
        </el-tag>
      </div>

      <div class="friends-chosed-btns">
        <el-button style="background-color: #fff; color: #999999" size="mini" @click="$parent.togglePage">
          返回
        </el-button>
        <el-button style="background-color: #ff9f00; color: white" size="mini" @click="nextStep">下一步</el-button>
      </div>
    </div>

    <!-- 编辑内容 -->
    <el-dialog
      title="编辑内容"
      :close-on-click-modal="false"
      :show-close="false"
      append-to-body
      class="add-group-send-dialog-2"
      :visible.sync="addGroupSendDialog"
    >
      <!-- aside -->
      <ul class="add-reply-aside">
        <li
          v-for="(mt, index) in msgTypes"
          :key="index"
          :class="{ 'li-selected': msgType === mt.type }"
          @click="msgType = mt.type"
        >
          <i class="fa" :class="mt.icon" aria-hidden="true"></i>
          {{ mt.name }}
        </li>
        <li @click="showAndQueryResources">
          <i style="color: green; font-size: 14px; cursor: pointer" class="el-icon-folder" title="素材库"></i>
          素材库
        </li>
      </ul>

      <Expression v-if="msgType === 'Text'" class="qq-expression" @expressionContent="modifyContent" />

      <!-- 文本 -->
      <el-input
        v-if="msgType === 'Text'"
        v-model.trim="textContent"
        type="textarea"
        placeholder="请输入内容"
        maxlength="500"
        show-word-limit
        resize="none"
      ></el-input>

      <!-- content -->
      <div v-else class="add-reply-content">
        <!-- 图片 -->
        <template v-if="msgType === 'Picture'">
          <template v-if="!pictureUrl">
            <img style="margin-top: 30px" src="../../../assets/images/circles/tianjiatupian.png" alt="" />
            <label style="cursor: pointer; padding: 5px" for="addPicture">
              <i class="el-icon-plus"></i>
              <span style="color: #576c95; font-size: 14px">添加图片</span>
            </label>
            <input
              v-show="false"
              id="addPicture"
              ref="pictureInputRef"
              type="file"
              accept=".jpg, .png, .jpeg"
              @change="chosePicture"
            />
          </template>
          <template v-else>
            <img style="max-width: 400px; max-height: 190px" :src="pictureUrl" alt="图片" />
            <div style="display: flex; align-items: center; height: 32px">
              <p style="margin-right: 5px" v-text="pictureName"></p>
              <i style="cursor: pointer" class="el-icon-delete" @click="deletePicture"></i>
            </div>
          </template>
        </template>
        <!-- 语音 -->
        <template v-else-if="msgType === 'Voice'">
          <template v-if="!voiceUrl">
            <img style="margin-top: 30px" src="../../../assets/images/circles/tianjiashipin.png" alt="" />
            <label style="cursor: pointer; padding: 5px" for="addVoice">
              <i class="el-icon-plus"></i>
              <span style="color: #576c95; font-size: 14px">添加语音</span>
            </label>
            <input
              v-show="false"
              id="addVoice"
              ref="voiceInputRef"
              type="file"
              accept=".mp3, .amr"
              @change="choseVoice"
            />
          </template>
          <template v-else>
            <audio style="max-width: 400px; max-height: 190px; margin-top: 60px" :src="voicePlayUrl" controls></audio>
            <div style="display: flex; align-items: center; height: 32px">
              <p style="margin-right: 5px" v-text="voiceName"></p>
              <i style="cursor: pointer" class="el-icon-delete" @click="deleteVoice"></i>
            </div>
          </template>
        </template>
        <!-- 视频 -->
        <template v-else-if="msgType === 'Video'">
          <template v-if="!videoUrl">
            <img style="margin-top: 30px" src="../../../assets/images/circles/tianjiashipin.png" alt="" />
            <label style="cursor: pointer; padding: 5px" for="addPicture">
              <i class="el-icon-plus"></i>
              <span style="color: #576c95; font-size: 14px">添加视频</span>
            </label>
            <input v-show="false" id="addPicture" ref="videoInputRef" type="file" accept=".mp4" @change="choseVideo" />
          </template>
          <template v-else>
            <video style="max-width: 400px; max-height: 190px" :src="videoUrl" controls></video>
            <div style="display: flex; align-items: center; height: 32px">
              <p style="margin-right: 5px" v-text="videoName"></p>
              <i style="cursor: pointer" class="el-icon-delete" @click="deleteVideo"></i>
            </div>
          </template>
        </template>

        <!-- link -->
        <el-form
          v-else-if="msgType === 'Link'"
          ref="linkDialog"
          :model="linkForm"
          :rules="linkRules"
          label-width="110px"
        >
          <el-form-item v-for="(link, index) in linkForm" :key="'link' + index" :label="linkName[index]" :prop="index">
            <el-input v-model="linkForm[index]" :disabled="index === 'TypeStr'" clearable></el-input>
          </el-form-item>
        </el-form>
        <!-- weapp -->
        <el-form
          v-else-if="msgType === 'WeApp'"
          ref="weappDialog"
          :model="weapp"
          :rules="weappRules"
          label-width="110px"
        >
          <el-form-item v-for="(wa, index) in weapp" :key="'weapp' + index" :label="index" :prop="index">
            <el-input v-model="weapp[index]" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- footer -->
      <span slot="footer">
        <!-- 备注 -->
        <el-input
          v-model="remarks"
          style="margin-bottom: 5px"
          clearable
          size="mini"
          placeholder="请输入备注"
          maxlength="50"
          show-word-limit
        ></el-input>

        <el-radio-group v-model="timeRadio" style="margin-left: 10px">
          <el-radio style="margin-right: 20px" :label="'rightNow'">立即发送</el-radio>
          <el-radio :label="'timing'">定时发送</el-radio>
          <el-date-picker
            v-model="refTime"
            style="width: 200px"
            type="datetime"
            placeholder="选择日期时间"
            clearable
            size="mini"
            :disabled="timeRadio === 'rightNow'"
          ></el-date-picker>
        </el-radio-group>
        <!-- 发时间隔 -->
        <span style="font-size: 14px; margin-left: 10px; color: #606266">间隔</span>
        <el-input-number
          v-model="betweenTime"
          style="width: 100px; margin-left: 5px"
          size="mini"
          controls-position="right"
          :min="10"
          :max="600"
        ></el-input-number>

        <el-button style="margin-left: 10px; color: #999999" size="mini" @click="resetData">取 消</el-button>
        <el-button
          style="background-color: #ff9f00; border: solid #ff9f00 1px"
          type="primary"
          size="mini"
          @click="sureSend"
        >
          发 送
        </el-button>
      </span>
    </el-dialog>

    <!-- 资源dialog -->
    <el-dialog
      title="选择群发素材"
      :close-on-click-modal="false"
      :show-close="false"
      append-to-body
      class="create-circle-resource"
      :visible.sync="showResources"
    >
      <!-- 资源列表 -->
      <el-table :data="resourcesDataList" stripe class="group-send-log-table" height="100%">
        <el-table-column label="素材类型" width="100">
          <template slot-scope="scope">
            <span v-text="tasktypeMap[scope.row.type]"></span>
          </template>
        </el-table-column>
        <el-table-column label="消息类型" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.restype" v-text="restypeMap[scope.row.restype]"></span>
            <span v-else v-text="scope.row.circleType"></span>
          </template>
        </el-table-column>
        <el-table-column label="素材内容">
          <template slot-scope="scope">
            <div
              :class="[
                {
                  'chat-link': scope.row.restype === 6
                },
                {
                  'chat-app': scope.row.restype === 13
                }
              ]"
              v-html="decodeChat(scope.row)"
            ></div>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks" width="100"></el-table-column>
        <el-table-column label="创建时间" width="100">
          <template slot-scope="scope">
            <span v-text="$options.filters.transformTime2Minute(scope.row.createTime)"></span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100">
          <template slot-scope="{ row }">
            <el-button size="mini" @click="choseItem(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin: 5px"
        :current-page="currentPage"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="pageSize"
        :pager-count="7"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
        @size-change="handleResourcesSizeChange"
        @current-change="handleResourcesCurrentChange"
      ></el-pagination>

      <!-- footer -->
      <span slot="footer">
        <el-button style="margin-left: 650px; color: #999999" size="mini" @click="showResources = false">
          取 消
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import { fileUpload } from '@/utils/upload'
import { uniqueArryList } from '@/utils/util.js'
import { addTaskTimeInfo, resourcesList } from '@/api/httpApi'
const imgError = require('@/assets/svg/conversation-image-error.svg')
import Expression from '@/components/expression'

export default {
  name: 'GroupAssistantSend',
  components: {
    Expression
  },
  data() {
    return {
      remarks: '', // 备注
      addGroupSendDialog: false, // 展示添加群发的dialog
      msgTypes: [
        {
          type: 'Text',
          icon: 'fa-file-text-o',
          name: '文本'
        },
        {
          type: 'Picture',
          icon: 'fa-file-image-o',
          name: '图片'
        },
        {
          type: 'Voice',
          icon: 'fa-microphone',
          name: '语音'
        },
        {
          type: 'Video',
          icon: 'fa-video-camera',
          name: '视频'
        },
        {
          type: 'Link',
          icon: 'fa-link',
          name: '链接'
        },
        {
          type: 'WeApp',
          icon: 'fa-product-hunt',
          name: '小程序'
        }
      ], // 消息类型
      msgType: 'Text', // 要群发的类型
      textContent: '', // 要群发的文本内容
      pictureUrl: '', // 要群发的图片url
      pictureName: '', // 要群发的图片名字
      voiceUrl: '', // 要群发的语音url
      voicePlayUrl: '', // 播放的语音
      voiceName: '', // 要群发的语音名字
      videoUrl: '', // 要群发的视频url
      videoName: '', // 要群发的视频名字
      weapp: {
        AppId: 'wxe99ba6e7fa3e8672',
        SourceName: 'gh_5b0c2f762fc0@app',
        Icon: 'http://wx.qlogo.cn/mmhead/Q3auHgzwzM5bBMPvk6Oohdlo4FpjGgLsTtcSYJKhibnoQWFphTVy7Bw/96',
        Source: '建业+',
        Title: '考拉之选 点断保鲜膜 食品级材质',
        Thumb:
          'http://gaia-projectc.oss-cn-hangzhou.aliyuncs.com/wxid_9988ti1oz81g22%2Fth_2fb4cbd7008c2e3cc33f6e49573c00cc.jpg',
        PagePath:
          'pages/index/index.html?_type=h5Link&h5url=https%3A%2F%2Fmall.yijiahn.com%2Fmall%2Fapp%2Fstatic%2Fgoods%2F3711147.html%3Fid%3D3711147&sharedUserId=2269485'
        // 'Des': '',
      }, // 小程序demo
      weappRules: {
        AppId: [{ required: true, message: '请输入AppId', trigger: 'blur' }],
        SourceName: [{ required: true, message: '请输入SourceName', trigger: 'blur' }],
        Icon: [{ required: true, message: '请输入Icon', trigger: 'blur' }],
        PagePath: [{ required: true, message: '请输入PagePath', trigger: 'blur' }],
        // Source: [
        //   { required: true, message: '请输入Source', trigger: 'blur' },
        // ],
        Title: [{ required: true, message: '请输入Title', trigger: 'blur' }],
        Thumb: [{ required: true, message: '请输入Thumb', trigger: 'blur' }]
      }, // 小程序表单验证
      linkForm: {
        Title: '“关闭领馆”落下帷幕! 外媒: 他们不再含泪抗议, 而是在大使馆前笑着合影',
        Thumb: 'http://www.jjldkj.com/files/phone/files/20200730/935FC7F27A771E914BD47DC261385309.jpg',
        Url: 'https://iflow.uc.cn/webview/news?app=meitullq-iflow&aid=17561738358438069514&cid=100&zzd_from=meitullq-iflow&uc_param_str=dndsfrvesvntnwpfgibicp&recoid=2043722754382504392&rd_type=reco&sp_gz=0&activity=1&activity2=1&dn=cf9807c357d1e8561c9aef3f75f05e71&enuid=AAPTn90AUlH8qpsGXMgpzgD%2BzWybOCOjkJX%2B2Ou9k8Lrzg%3D%3D&uc_iflow_biz=cmt%3A1&imei=bTkwAA3esoPsTi%2Ff%2FLrBSXG9zpdQ2YF7sw%3D%3D',
        Des: '震惊Des',
        TypeStr: '[链接]'
      }, // 链接demo
      linkRules: {
        Title: [{ required: true, message: '请输入Title', trigger: 'blur' }],
        Thumb: [{ required: true, message: '请输入Thumb', trigger: 'blur' }],
        Url: [{ required: true, message: '请输入Url', trigger: 'blur' }],
        Des: [{ required: true, message: '请输入Des', trigger: 'blur' }]
      }, // 链接表单验证
      linkName: {
        Title: '链接标题',
        Thumb: '图片网址',
        Url: '链接地址',
        Des: '链接描述'
      }, // 链接字段对应的中文
      timeRadio: 'rightNow', // 立即发送还是定时发送
      refTime: new Date().getTime(),

      searchContent: '', // 搜索框的内容
      currentTab: 'friendsTab', // 默认是群发好友
      currentLabel: 'allFriends', // 要展示的好友标签
      tableData: [], // 表数据 默认展示全部的好友
      friendsChecked: [], // 已选择的好友的id
      friendsCheckedByLabel: {}, // 每个label选中的好友
      finalFriends: [], // 计算最终选中的好友
      forceRefresh: true, // 重新渲染表格 强制数据刷新
      currentRoomLabel: 'allFriends', // 要展示的好友标签
      roomsChecked: [], // 选择的群
      betweenTime: 15, // 群发消息的时间间隔
      currentPage: 1,
      pageSize: 50,

      showResources: false,
      resourcesPageSize: 20,
      resourcesCurrentPage: 1,
      totalNum: 0,
      tasktypeMap: {
        1: '群发素材',
        2: '朋友圈素材',
        3: '链接素材',
        4: '小程序素材'
      }, // 任务类型
      restypeMap: {
        Text: 1,
        Picture: 2,
        Voice: 3,
        Video: 4,
        Link: 6,
        WeApp: 13,
        1: '文本',
        2: '图片',
        3: '语音',
        4: '视频',
        6: '链接',
        13: '小程序'
      }, // 消息类型
      resourcesDataList: [] // 素材列表
    }
  },
  computed: {
    ...mapState('nedb', {
      labels: 'labels',
      friends: 'friends',
      chatRooms: 'chatRooms'
    }),
    ...mapGetters({
      currentUser: 'currentUser',
      currentWeChatId: 'conversation/currentWeChatId',
      currentFriend: 'conversation/currentFriend',
      labelNameMap: 'nedb/labelNameMap',
      labelIdMap: 'nedb/labelIdMap'
    }),
    // 每个label下的好友
    friendsOfEveryLabel() {
      const felm = {}
      for (const label of this.labels) {
        felm[label.LabelId] = this.friends.filter((x) => {
          return x.LabelIds && x.LabelIds.indexOf(String(label.LabelId)) >= 0
        })
      }
      return felm
    },
    // 选择的好友
    finalFriendsInfo() {
      const ffi = []
      this.friends.forEach((x) => {
        if (this.finalFriends.indexOf(x.FriendId) >= 0) {
          ffi.push(x)
        }
      })
      return ffi
    },
    // 选中的群的信息
    roomsCheckedInfo() {
      const ffi = []
      this.chatRooms.forEach((x) => {
        if (this.roomsChecked.indexOf(x.UserName) >= 0) {
          ffi.push(x)
        }
      })
      return ffi
    },
    // 表数据分页展示
    tableDataPage() {
      // 分页 每页50
      const size = this.pageSize
      const newData = []
      for (let i = 0; i < this.tableData.length; i += size) {
        newData.push(this.tableData.slice(i, i + size))
      }
      return newData
    }
  },
  watch: {
    // 监听搜索栏
    searchContent(sc) {
      if (sc) {
        this.tableData = this.friends.filter((x) => {
          // 昵称
          if (x.FriendNick) {
            return x.FriendNick.indexOf(this.searchContent) >= 0
          }
          // 备注
          if (x.Memo) {
            return x.Memo.indexOf(this.searchContent) >= 0
          }
          // 群名
          if (x.NickName) {
            return x.NickName.indexOf(this.searchContent) >= 0
          }
          // 陌生人
          if (x.Nickname) {
            return x.Nickname.indexOf(this.searchContent) >= 0
          }
        })
      } else {
        this.tableData = this.friends
      }
    },
    // 监听微信改变
    currentWeChatId() {
      this.tableData = this.friends
      this.currentLabel = 'allFriends'
      this.currentRoomLabel = 'allFriends'
    },
    labels() {
      this.initData()
    }
  },
  created() {
    // 初始化数据
    this.initData()
  },
  methods: {
    // 添加表情
    modifyContent(rm) {
      this.textContent = this.textContent + rm
    },
    // 改pageSize
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.currentPage = val
    },
    // 初始化数据
    initData() {
      this.tableData = this.friends
      for (const label of this.labels) {
        this.friendsOfEveryLabel[label.LabelId] = this.friends.filter((x) => {
          return x.LabelIds && x.LabelIds.indexOf(String(label.LabelId)) >= 0
        })
        this.friendsCheckedByLabel[label.LabelId] = []
      }
    },
    // 计算序号
    indexMethod(index) {
      return index + 1
    },
    // 展示数据
    showFriends(labelId) {
      if (labelId === 'allFriends') {
        this.tableData = this.friends
      } else {
        this.tableData = this.friends.filter((x) => {
          return x.LabelIds && x.LabelIds.indexOf(String(labelId)) >= 0
        })
      }
      this.currentLabel = labelId
    },
    // 计算选中的好友
    computedFriends() {
      let cfs = [].concat(this.friendsChecked)
      for (const key in this.friendsCheckedByLabel) {
        if (Object.hasOwnProperty.call(this.friendsCheckedByLabel, key)) {
          cfs = cfs.concat(this.friendsCheckedByLabel[key])
        }
      }
      this.finalFriends = uniqueArryList(cfs, 'FriendId')
    },
    // 选中标签
    choseFriendsByLabel(e, labelId) {
      if (labelId === 'allFriends') {
        if (this.friendsChecked.length === this.friends.length) {
          // 全不选
          this.friendsChecked = []
          // 重置每个label的选中的微信
          for (const key in this.friendsCheckedByLabel) {
            if (Object.hasOwnProperty.call(this.friendsCheckedByLabel, key)) {
              this.friendsCheckedByLabel[key] = []
            }
          }
        } else {
          // 全选
          this.friends.forEach((x) => {
            if (this.friendsChecked.indexOf(x.FriendId) < 0) {
              this.friendsChecked.push(x.FriendId)
            }
          })
          // 全选每个label的好友
          for (const key in this.friendsOfEveryLabel) {
            if (Object.hasOwnProperty.call(this.friendsOfEveryLabel, key)) {
              const element = this.friendsOfEveryLabel[key]
              this.friendsCheckedByLabel[key] = element.map((x) => {
                return x.FriendId
              })
            }
          }
        }
      } else {
        if (this.friendsOfEveryLabel[labelId].length === 0) {
          e.preventDefault()
          return
        }
        const currentFriends = this.friendsOfEveryLabel[labelId]
        const currentChoseFriends = this.friendsCheckedByLabel[labelId]
        if (currentFriends.length === currentChoseFriends.length) {
          this.friendsCheckedByLabel[labelId] = []
        } else {
          currentFriends.forEach((x) => {
            if (currentChoseFriends.indexOf(x.FriendId) < 0) {
              currentChoseFriends.push(x.FriendId)
            }
          })
        }
      }
      this.computedFriends()
    },
    // table中的单选
    choseFriend(e, friend) {
      const friendId = friend.FriendId
      const labelId = this.currentLabel
      if (this.currentLabel === 'allFriends') {
        const fid = this.friendsChecked.indexOf(friendId)
        if (fid >= 0) {
          // 移除
          this.friendsChecked.splice(fid, 1)
        } else {
          // 添加
          this.friendsChecked.push(friendId)
        }
      } else {
        const fid = this.friendsCheckedByLabel[labelId].indexOf(friendId)
        if (fid >= 0) {
          // 移除
          this.friendsCheckedByLabel[labelId].splice(fid, 1)
        } else {
          // 添加
          this.friendsCheckedByLabel[labelId].push(friendId)
        }
        // 重新渲染组件
        this.$forceUpdate()
      }
      this.computedFriends()
    },
    // 群聊 选中标签
    choseRoomsByLabel(e, labelId) {
      if (labelId === 'allFriends') {
        if (this.roomsChecked.length === this.chatRooms.length) {
          // 全不选
          this.roomsChecked = []
        } else {
          // 全选
          this.chatRooms.forEach((x) => {
            if (this.roomsChecked.indexOf(x.UserName) < 0) {
              this.roomsChecked.push(x.UserName)
            }
          })
        }
      }
    },
    // 选择群聊
    choseRoom(e, room) {
      const rid = this.roomsChecked.indexOf(room.UserName)
      if (this.currentRoomLabel === 'allFriends') {
        if (rid >= 0) {
          // 移除
          this.roomsChecked.splice(rid, 1)
        } else {
          // 添加
          this.roomsChecked.push(room.UserName)
        }
      }
    },
    // 移除选择的好友
    removeFriend(friend) {
      const friendId = friend.FriendId
      const fid = this.friendsChecked.indexOf(friendId)
      // 移除friendsChecked中的数据
      if (fid >= 0) {
        this.friendsChecked.splice(fid, 1)
      }
      this.forceRefresh = false
      // 移除每个label的选择
      for (const key in this.friendsCheckedByLabel) {
        if (Object.hasOwnProperty.call(this.friendsCheckedByLabel, key)) {
          const fcd = this.friendsCheckedByLabel[key]
          const fcdid = fcd.indexOf(friendId)
          if (fcdid >= 0) {
            fcd.splice(fid, 1)
          }
        }
      }
      setTimeout(() => {
        this.forceRefresh = true
      }, 50)
      // 重新渲染组件
      this.$forceUpdate()
      // 重新计算选择的好友
      this.computedFriends()
    },
    // 移除room
    removeRoom(room) {
      this.roomsChecked.splice(this.roomsChecked.indexOf(room.UserName), 1)
    },
    // 下一步
    nextStep() {
      if (this.currentTab === 'friendsTab' && this.finalFriends.length === 0) {
        this.$alert('请选选择发送的对象！', '提示', { type: 'warning' })
        return
      }
      if (this.currentTab === 'roomsTab' && this.roomsChecked.length === 0) {
        this.$alert('请选选择发送的对象！', '提示', { type: 'warning' })
        return
      }
      this.addGroupSendDialog = true
    },
    // 取消
    resetData() {
      this.addGroupSendDialog = false
    },
    // 选择图片
    chosePicture() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.pictureInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        // image/jpeg
        const isImage = file.type.indexOf('image') >= 0
        const isLt2M = file.size > 0 && file.size / 1024 / 1024 < 20

        if (!isImage) {
          this.$alert('图片格式不对！', '提示', { type: 'warning' })
          return
        }
        if (!isLt2M) {
          this.$alert('上传图片大小不能超过 20MB!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)
        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.pictureName = file.name // 文件名
            this.pictureUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除图片
    deletePicture() {
      this.pictureName = ''
      this.pictureUrl = ''
    },
    // 选择图片
    choseVideo() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.videoInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        const isMP4 = file.type === 'video/mp4'
        const isLt2M = file.size > 0 && file.size / 1024 / 1024 < 20
        if (!isMP4) {
          this.$alert('上传视频只能是 MP4 格式!', '提示', { type: 'warning' })
          return
        }
        if (!isLt2M) {
          this.$alert('上传视频大小不能超过 20MB!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)
        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.videoName = file.name // 文件名
            this.videoUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除图片
    deleteVideo() {
      this.videoUrl = ''
      this.videoName = ''
    },
    // 选择语音
    choseVoice() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.voiceInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        const fileSize = file.size
        const fileName = file.name
        const fileType = fileName.replace(/.+\./, '').toLowerCase()
        // 文件大于10M不能发送
        if (fileSize > 104857600 || fileSize <= 0) {
          this.$alert('语音大小不能超过 10MB!', '提示', { type: 'warning' })
          return
        }
        // 验证文件类型
        if (['amr', 'mp3'].indexOf(fileType) < 0) {
          this.$alert('语音格式不对!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)

        // 如果选择的是mp3文件，文件上传到服务器，转为amr，返回amr的地址
        // 如果选择的是amr文件，直接上传到服务器，返回amr的地址
        if (fileType === 'mp3') {
          formdata.append('isMp3ToAmr', true)
        } else if (fileType === 'amr') {
          formdata.append('isAmrToMp3', false)
        }

        // 上传mp3 或者amr转为MP3
        const formDataMp3 = new FormData()
        formDataMp3.append('myfile', fileObj[0])
        if (fileType === 'mp3') {
          formDataMp3.append('isMp3ToAmr', false)
        } else if (fileType === 'amr') {
          formDataMp3.append('isAmrToMp3', true)
        }
        fileUpload(formDataMp3)
          .then((res) => {
            setTimeout(() => {
              this.voicePlayUrl = res.data.url
            }, 2000)
          })
          .catch((err) => {
            this.$message.error(err)
          })

        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.voiceName = file.name // 文件名
            this.voiceUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除语音
    deleteVoice() {
      this.voiceUrl = ''
      this.voiceName = ''
    },
    // 定时群发 时间转换
    transformTime(times) {
      const date = new Date(times)
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      // let s = date.getSeconds()
      const time = Y + M + D + h + m
      return time
    },
    // 发送
    sureSend() {
      let msgContent = this.textContent // 发送的内容 默认是文本内容
      const target2Send = this.currentTab === 'friendsTab' ? this.finalFriends : this.roomsChecked // 发给谁
      const startTime = this.timeRadio === 'timing' ? this.refTime : new Date().getTime() // 发送的起始时间

      // 后端限制数组不能超过5000
      if (target2Send.length > 5000) {
        this.$alert('群发不能超过5000人！', '提示', { type: 'warning' })
        return
      }

      if (this.msgType === 'Picture') {
        msgContent = this.pictureUrl
      } else if (this.msgType === 'Voice') {
        msgContent = this.voiceUrl
      } else if (this.msgType === 'Video') {
        msgContent = this.videoUrl
      } else if (this.msgType === 'Link') {
        msgContent = JSON.stringify(this.linkForm)
      } else if (this.msgType === 'WeApp') {
        msgContent = JSON.stringify(this.weapp)
      }

      // 发送的内容不能为空
      if (msgContent.length === 0) {
        this.$alert('内容不能为空！', '提示', { type: 'warning' })
        return
      }
      // 发送的对象不能为空
      if (target2Send.length === 0) {
        this.$alert('请选择发送的对象！', '提示', { type: 'warning' })
        return
      }
      // restype
      const typeMap = {
        Text: 1,
        Picture: 2,
        Voice: 3,
        Video: 4,
        Link: 6,
        WeApp: 13
      }
      const message = {
        accountid: this.$store.getters.currentUser.UnionId,
        tasktype: this.currentTab === 'friendsTab' ? 1 : 5, // 1:群发好友 5:群发群
        state: 1, // 状态1开启中0已完成
        wechatId: this.currentWeChatId, // 要执行的微信号
        wechatList: target2Send, // 好友的微信号
        execute_time: this.transformTime(startTime), // 执行时间
        restype: typeMap[this.msgType], // 资源类型
        content: msgContent, // 内容
        between_time: this.betweenTime // 发消息间隔时间
      }
      message.remarks = this.remarks
      addTaskTimeInfo(message)
        .then((res) => {
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '创建定时任务成功！',
              duration: 1000
            })
            this.resetData()
          } else {
            this.$message({
              type: 'error',
              message: '创建定时任务失败！',
              duration: 1000
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
      this.$parent.togglePage()
    },
    // 查询素材
    queryResourceData() {
      resourcesList(this.currentUser.SupplierId, this.resourcesCurrentPage, this.resourcesPageSize, 1).then((res) => {
        if (res.code === 0 && res.data.rows) {
          this.resourcesDataList = res.data.rows.map((x) => {
            const jc = JSON.parse(x.content)
            jc.id = x.id
            jc.cid = x.cid
            jc.createTime = x.createTime
            jc.remarks = x.remarks
            return jc
          })
          this.totalNum = res.data.records || 0
        } else {
          this.resourcesDataList = []
          this.totalNum = 0
        }
      })
    },
    // 查询并展示素材
    showAndQueryResources() {
      resourcesList(this.currentUser.SupplierId, this.resourcesCurrentPage, this.resourcesPageSize, 1).then((res) => {
        if (res.code === 0 && res.data.rows) {
          this.resourcesDataList = res.data.rows.map((x) => {
            const jc = JSON.parse(x.content)
            jc.id = x.id
            jc.cid = x.cid
            jc.createTime = x.createTime
            jc.type = x.type
            jc.remarks = x.remarks
            if (x.attachtype) {
              jc.attachtype = x.attachtype
            }
            if (x.attachtcontent) {
              jc.attachtcontent = x.attachtcontent
            }
            return jc
          })
          this.totalNum = res.data.records || 0
          this.showResources = true
        } else {
          this.resourcesDataList = []
          this.totalNum = 0
          this.showResources = true
        }
      })
    },
    // 选择素材素材
    choseItem(row) {
      // restype
      const restypeMap = {
        1: 'Text',
        2: 'Picture',
        3: 'Voice',
        4: 'Video',
        6: 'Link',
        13: 'WeApp'
      }
      this.msgType = restypeMap[row.restype]
      if (row.restype === 1) {
        this.textContent = row.content
      } else if (row.restype === 2) {
        this.pictureUrl = row.content
      } else if (row.restype === 3) {
        this.voiceUrl = row.content
      } else if (row.restype === 4) {
        this.videoUrl = row.content
      } else if (row.restype === 6) {
        this.linkForm = JSON.parse(row.content)
      } else if (row.restype === 13) {
        this.weapp = JSON.parse(row.content)
      }
      this.showResources = false
    },
    // 修改pageSize
    handleResourcesSizeChange(val) {
      if (this.resourcesPageSize === val) return
      this.resourcesPageSize = val
      this.queryResourceData()
    },
    // 修改当前页
    handleResourcesCurrentChange(val) {
      this.resourcesCurrentPage = val
      this.queryResourceData()
    },
    // 解析内容
    decodeChat(chat) {
      const content = chat.content
      const regJson = new RegExp(/^{.+}$/)
      let jContent = {}
      if (regJson.test(content)) {
        jContent = JSON.parse(content)
      }
      let thumb = ''
      let str = ''
      switch (chat.restype) {
        // 文本 1
        case 'Text':
        case 1:
          return content
        // 图片 2
        case 'Picture':
        case 2:
          return `<img style="width:100px;" src="${content}"  alt="图片"/>`
        // 语音 3
        case 'Voice':
        case 3:
          if (content.endsWith('.amr')) {
            thumb = content.replace(/.amr$/, '.mp3')
          } else {
            thumb = content.replace(/.mp3:[0-9]+/, '.mp3')
          }
          return `<audio src="${thumb}" alt="语音" controls></audio>`
        // 视频 4
        case 'Video':
        case 4:
          return `<video class="video-box" src="${content}" type="video/mp4" alt="视频" controls></video>`
        // 链接消息 6
        case 'Link':
        case 6:
          str = `
                    <span class="link-title">${jContent.Title}</span>
                    <div class="link-content">
                      <span class="link-des">${jContent.Des}</span>
                      <img class="link-img" src="${jContent.Thumb}" alt="链接图片" />
                    </div>
                    <div class="link-type">${jContent.TypeStr}</div>
                    `
          return str

        // 小程序 13
        case 'WeApp':
        case 13: {
          let appIcon = imgError
          let appSource = '无效小程序'
          let appTitle = '无效小程序'
          let appThumb = ''
          let appTypeStr = '小程序'
          if (typeof content === 'string' && regJson.test(content)) {
            jContent = JSON.parse(content)
            appIcon = jContent.Icon && typeof jContent.Icon !== 'undefined' ? jContent.Icon : imgError
            appSource = jContent.Source
            appTitle = jContent.Title || jContent.Des
            appThumb = jContent.Thumb
            appTypeStr = jContent.TypeStr ? jContent.TypeStr : '小程序'
          }

          str = `
              <div class="app-des">
              <img class="app-icon" src="${appIcon}" alt="icon" />
              <span class="app-source ellipsis">${appSource}</span>
              </div>
              <div class="app-title ellipsis">${appTitle}</div>
              <img class="app-img" src="${appThumb}" />
              <div class="app-typestr">${appTypeStr}</div>
               `
          return str
          // return jContent
        }

        // 不支持的消息
        default:
          return `不支持的消息类型${chat.ContentType}`
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.group-send {
  flex: 1 1 auto;
  display: flex;
  overflow: hidden;

  .filter-box {
    width: 189px;
    min-width: 189px;
    height: 100%;
    padding: 5px 5px 0 5px;
    border: solid #eeeeee 1px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .tab-title {
      width: 100%;
      display: flex;
      p {
        width: 50%;
        height: 40px;
        color: #999999;
        font-size: 14px;
        line-height: 40px;
        font-weight: 500;
        cursor: pointer;
        text-align: center;
        border-bottom: solid #dddddd 1px;
      }
      .tabChose {
        color: #ff9f00;
        border-bottom: solid #ff9f00 1px;
      }
    }

    .labels-list {
      width: 100%;
      flex: 1 1 auto;
      overflow: auto;

      .label-item {
        display: flex;
        align-items: center;
        color: #333333;
        font-size: 14px;
        height: 26px;
        cursor: pointer;
        p {
          margin-left: 5px;
          width: 150px;
          height: 26px;
          line-height: 26px;
        }
      }
      .current-label {
        color: #ff9f00;
      }
      .label-disabled {
        color: #c0c4cc;
        cursor: not-allowed;
        input {
          cursor: not-allowed;
          color: #c0c4cc;
          border: solid #c0c4cc 1px;
        }
      }
    }
  }

  .friends-list {
    // width: 722px;
    flex: 1 1 auto;
    height: 100%;
    padding: 10px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .friends-list-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 0 10px 0;
      p {
        font-size: 14px;
        color: #999999;
      }
      .search-input {
        width: 200px;
        height: 32px;
        // .el-input__inner {
        //   height: 28px;
        //   line-height: 28px;
        //   color: #dadada;
        //   font-size: 12px;
        //   padding-left: 5px;
        // }
      }
    }

    ::v-deep .el-table {
      width: 100%;
      height: 100%;
      overflow: auto;
      .el-table__header-wrapper {
        // min-height: 60px;
        min-height: 40px;
        display: flex;
        align-items: center;
        background-color: #ff9f000d;

        .el-table__header {
          th {
            background-color: #ff9f000d;
            padding: 0;
            border-bottom: none;
          }
        }
      }
      td {
        padding: 5px;
      }
    }
  }

  .chat-rooms-list {
    flex: 1 1 auto;
    padding: 14px;
    overflow: auto;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;

    .room-item {
      width: 213px;
      height: 58px;
      border-radius: 5px;
      margin: 0 16px 16px 0;
      background-color: #f7f7f5;
      display: flex;
      align-items: center;
      padding: 0 17px;
      p {
        width: 150px;
      }
    }
    .room-item-3x {
      margin-right: 0;
    }
  }

  .friends-chosed {
    width: 209px;
    min-width: 209px;
    display: flex;
    flex-direction: column;
    border-left: solid #eeeeee 1px;

    .third-box-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
      color: #333333;
      padding: 5px;
      height: 40px;
      line-height: 40px;
      // border: solid red 1px;
    }
    .friends-chose-list {
      flex: 1 1 auto;
      overflow: auto;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
    }
    .friends-chosed-btns {
      height: 50px;
      min-height: 50px;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #f9f9f9;
      .el-button {
        width: 82px;
        height: 32px;
      }
    }
  }
}

.qq-expression {
  padding: 2px;
  position: absolute;
  left: 100px;
  top: 250px;
}

::v-deep .chat-link {
  flex-direction: column;
  width: 300px;
  max-width: 100%;
  cursor: pointer;
  .link-title {
    font-size: 14px;
    font-weight: 600;
  }
  .link-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .link-des {
      flex: auto;
      color: #aaaaaa;
      font-size: 10px;
      margin-right: 5px;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
      word-wrap: break-word;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
    }
    .link-img {
      max-width: 50px;
      max-height: 50px;
      min-height: 50px;
      min-width: 50px;
      border-radius: 5px;
    }
  }
  .link-type {
    color: #aaaaaa;
    margin-top: 5px;
    text-align: start;
    border-top: solid #e8eaec 1px;
  }
}
::v-deep .chat-app {
  width: 300px;
  max-width: 100%;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  .app-des {
    display: flex;
    .app-icon {
      width: 20px;
      height: 20px;
    }
    .app-source {
      width: 100%;
      font-size: 12px;
      margin-left: 5px;
      color: gray;
    }
  }
  .app-title {
    width: 100%;
    height: 30px;
    font-size: 12px;
    font-weight: 600;
    line-height: 30px;
  }
  .app-img {
    align-self: center;
    max-width: 200px;
  }
  .app-typestr {
    height: 25px;
    margin-top: 5px;
    line-height: 25px;
    color: gray;
    text-align: start;
    border-top: solid #aaaaaa 1px;
  }
}
</style>

